//http://www.java2s.com/Code/Java/Threads/Definingathreadforathreadpool.htm

import java.util.LinkedList;


public class ThreadPool {
	// List with tasks to be executed
	private LinkedList<Runnable> tasks = new LinkedList<Runnable>();
	// All threads
	private WorkerThread[] threads;

	/*
	 * Default consturctor which creates 4 worker threads.
	 */
	public ThreadPool() {
		threads = new  WorkerThread[4];
		for(int i=0;i<4;i++) {
			WorkerThread thread = new WorkerThread(this);
			threads[i] = thread;
			thread.start();
		}
	}
	
	public ThreadPool(int size) {
		threads = new  WorkerThread[size];
		// Create new idle treads
		for(int i=0;i<size;i++) {
			WorkerThread thread = new WorkerThread(this);
			// Add the thread to the list of threads
			threads[i] = thread;
			// Start the thread
			thread.start();
		}
	}
	
	public synchronized Runnable getTask() {
		while(tasks.isEmpty()) {
			try {
				// Wait for a new task to be added to the task list.
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		// Return the task to be executed and remove it from the task list.
		return tasks.removeLast();
		
	}
	
	
	public synchronized void add(Runnable task) {
		// Add new task to task list
		tasks.addFirst(task);	
		// Notify a waiting thread that a task is available
		notify();
	}
	
	public synchronized void stopPool() {
		// Interrupt all threads
		for(int i=0;i>threads.length;i++) {
			threads[i].interrupt();
		}
	}
}
